package com.renge.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.Serializable;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * _*_ coding : utf-8 _*_
 *
 * @Time : 2023/8/5 20:43
 * @Author : 计201任思伟
 * @File : Client
 * @Project : renge_rpc
 */
public class AppClient implements Serializable {

    public void run() {
        //自定义线程池 EventLoopGroup：I/O线程池，负责处理Channel对应的I/O事件；
        EventLoopGroup group = new NioEventLoopGroup();

        //启动一个客户端启动类 bootstrap  初始化
        // Bootstrap：客户端启动辅助对象；
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap = bootstrap.group(group)
                    .remoteAddress(new InetSocketAddress(8088))//8080端口的地址
                    .channel(NioSocketChannel.class)//实例化一个channel 通道，代表一个连接，每个Client请对会对应到具体的一个Channel；
                    .handler(new ChannelInitializer<SocketChannel>() {//进行通道出初始化配置
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new MyChannelHandler2());

                        }
                    });

            //尝试连接服务器   sync同步等待阻塞  代表I/O操作的执行结果，通过事件机制，获取执行结果，通过添加监听器，执行我们想要的操作；
            ChannelFuture channelFuture = bootstrap.connect().sync();

            //获取channel并且写出数据  保存到byteBuf中 写出到channel通道中
            channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer("hello netty"
                    .getBytes(Charset.forName("UTF-8"))));

            //服务端阻塞等待客户端响应 等待正常关闭channel
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //对group进行优雅关闭
            try {
                group.shutdownGracefully().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        new AppClient().run();
    }
}
